package fr.alesia.deepstack.servlet;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.alesia.deepstack.bean.Player;
import fr.alesia.deepstack.bean.Ranking;
import fr.alesia.deepstack.bean.Tournament;
import fr.alesia.deepstack.data.PlayerDao;
import fr.alesia.deepstack.data.RankingDao;
import fr.alesia.deepstack.data.TournamentDao;
import fr.alesia.deepstack.factory.DaoFactory;
import fr.alesia.deepstack.factory.ServiceFactory;

@SuppressWarnings("serial")
public class TournamentServlet extends HttpServlet {
	
	@Override
	protected void doGet(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		
		ServletContext context = this.getServletContext();
		TournamentDao tournamentDao = DaoFactory.getTournamentDao();
		RankingDao rankingDao = DaoFactory.getRankingDao();
		PlayerDao playerDao = DaoFactory.getPlayerDao();
		
		String id = request.getParameter("tournament-id");
		Tournament tournament = tournamentDao.find(id);
		int n = ServiceFactory.getTournamentService(tournament).getNbPlayers();
		Set<Ranking> rankings = new HashSet<Ranking>(n);
		
		for(int rank = 1 ; rank <= n ; rank ++){
			
			String name = request.getParameter("player" + rank);
			Player player = playerDao.findByName(name);
			Ranking ranking = rankingDao.find(tournament, player);
			ranking.setRank(rank);
			rankings.add(ranking);
			rankingDao.update(ranking);
		}
		
		request.setAttribute("rankings", rankings);
		
		RequestDispatcher dispatcher = context.getRequestDispatcher("/webapp/page/private/results.jsp");
		dispatcher.forward(request, response);
	}

	@Override
	protected void doPost (
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		
		this.doGet(request, response);
	}
}
